<template>
  <div class="finance-vouchers-container">
    <div class="page-header">
      <h2>凭证管理</h2>
      <button class="btn btn-primary" @click="showCreateModal = true">
        新增凭证
      </button>
    </div>

    <!-- 筛选条件 -->
    <div class="filter-section">
      <div class="filter-item">
        <label>会计期间:</label>
        <input type="month" v-model="filters.period" />
      </div>
      <div class="filter-item">
        <label>状态:</label>
        <select v-model="filters.status">
          <option value="">全部</option>
          <option value="DRAFT">草稿</option>
          <option value="POSTED">已过账</option>
        </select>
      </div>
      <button class="btn btn-secondary" @click="fetchVouchers">查询</button>
    </div>

    <!-- 凭证列表 -->
    <div class="table-container">
      <table class="data-table">
        <thead>
          <tr>
            <th>凭证号</th>
            <th>会计期间</th>
            <th>摘要</th>
            <th>状态</th>
            <th>创建时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="voucher in financeStore.vouchers" :key="voucher.id">
            <td>{{ voucher.voucher_no }}</td>
            <td>{{ voucher.period }}</td>
            <td>{{ voucher.summary }}</td>
            <td>
              <span :class="['status-badge', voucher.status.toLowerCase()]">
                {{ getStatusText(voucher.status) }}
              </span>
            </td>
            <td>{{ formatDateTime(voucher.created_at) }}</td>
            <td>
              <button class="btn btn-sm btn-info" @click="viewVoucher(voucher)">
                查看
              </button>
              <button 
                v-if="voucher.status === 'DRAFT'" 
                class="btn btn-sm btn-success" 
                @click="postVoucher(voucher)"
              >
                过账
              </button>
            </td>
          </tr>
          <tr v-if="financeStore.vouchers.length === 0">
            <td colspan="6" class="text-center">暂无数据</td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 新增凭证模态框 -->
    <div v-if="showCreateModal" class="modal-overlay" @click="showCreateModal = false">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>新增凭证</h3>
          <button class="modal-close" @click="showCreateModal = false">&times;</button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="createVoucher">
            <div class="form-group">
              <label>会计期间:</label>
              <input type="month" v-model="newVoucher.period" required />
            </div>
            <div class="form-group">
              <label>摘要:</label>
              <input type="text" v-model="newVoucher.summary" required />
            </div>
            
            <div class="entries-section">
              <h4>分录明细</h4>
              <div 
                v-for="(entry, index) in newVoucher.entries" 
                :key="index" 
                class="entry-item"
              >
                <div class="form-row">
                  <div class="form-group">
                    <label>科目:</label>
                    <select v-model="entry.subject_id" required>
                      <option value="">请选择科目</option>
                      <option 
                        v-for="subject in accountingSubjects" 
                        :key="subject.id" 
                        :value="subject.id"
                      >
                        {{ subject.code }} - {{ subject.name }}
                      </option>
                    </select>
                  </div>
                  <div class="form-group">
                    <label>借方金额:</label>
                    <input 
                      type="number" 
                      step="0.01" 
                      v-model="entry.debit_amount" 
                      @input="updateCreditAmount(index)"
                    />
                  </div>
                  <div class="form-group">
                    <label>贷方金额:</label>
                    <input 
                      type="number" 
                      step="0.01" 
                      v-model="entry.credit_amount" 
                      @input="updateDebitAmount(index)"
                    />
                  </div>
                  <div class="form-group">
                    <label>摘要:</label>
                    <input type="text" v-model="entry.description" />
                  </div>
                  <button 
                    type="button" 
                    class="btn btn-danger btn-sm remove-entry"
                    @click="removeEntry(index)"
                  >
                    删除
                  </button>
                </div>
              </div>
              <button 
                type="button" 
                class="btn btn-secondary" 
                @click="addEntry"
              >
                添加分录
              </button>
            </div>
            
            <div class="form-group balance-info">
              <p :class="{ 'unbalanced': !financeStore.isBalanced }">
                借方合计: {{ totalDebit.toFixed(2) }} | 
                贷方合计: {{ totalCredit.toFixed(2) }} | 
                差额: {{ (totalDebit - totalCredit).toFixed(2) }}
              </p>
            </div>
          </form>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="showCreateModal = false">取消</button>
          <button 
            class="btn btn-primary" 
            @click="createVoucher" 
            :disabled="!financeStore.isBalanced"
          >
            保存
          </button>
        </div>
      </div>
    </div>

    <!-- 查看凭证详情模态框 -->
    <div v-if="showDetailModal" class="modal-overlay" @click="showDetailModal = false">
      <div class="modal-content detail-modal" @click.stop>
        <div class="modal-header">
          <h3>凭证详情</h3>
          <button class="modal-close" @click="showDetailModal = false">&times;</button>
        </div>
        <div class="modal-body" v-if="financeStore.currentVoucher">
          <div class="voucher-info">
            <p><strong>凭证号:</strong> {{ financeStore.currentVoucher.voucher_no }}</p>
            <p><strong>会计期间:</strong> {{ financeStore.currentVoucher.period }}</p>
            <p><strong>摘要:</strong> {{ financeStore.currentVoucher.summary }}</p>
            <p><strong>状态:</strong> 
              <span :class="['status-badge', financeStore.currentVoucher.status.toLowerCase()]">
                {{ getStatusText(financeStore.currentVoucher.status) }}
              </span>
            </p>
            <p><strong>创建时间:</strong> {{ formatDateTime(financeStore.currentVoucher.created_at) }}</p>
          </div>
          
          <div class="entries-section">
            <h4>分录明细</h4>
            <table class="data-table">
              <thead>
                <tr>
                  <th>科目</th>
                  <th>借方金额</th>
                  <th>贷方金额</th>
                  <th>摘要</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="entry in financeStore.currentVoucher.entries" :key="entry.id">
                  <td>{{ entry.subject?.code }} - {{ entry.subject?.name }}</td>
                  <td>{{ entry.debit_amount?.toFixed(2) }}</td>
                  <td>{{ entry.credit_amount?.toFixed(2) }}</td>
                  <td>{{ entry.description }}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { useFinanceStore } from '@/stores/finance'
import { format } from 'date-fns'

export default {
  name: 'FinanceVouchers',
  setup() {
    const financeStore = useFinanceStore()
    
    // 状态
    const showCreateModal = ref(false)
    const showDetailModal = ref(false)
    const accountingSubjects = ref([])
    
    // 筛选条件
    const filters = reactive({
      period: '',
      status: ''
    })
    
    // 新增凭证数据
    const newVoucher = reactive({
      period: format(new Date(), 'yyyy-MM'),
      summary: '',
      entries: [
        {
          subject_id: '',
          debit_amount: 0,
          credit_amount: 0,
          description: ''
        }
      ]
    })
    
    // 计算借方和贷方合计
    const totalDebit = computed(() => {
      return newVoucher.entries.reduce((sum, entry) => sum + (parseFloat(entry.debit_amount) || 0), 0)
    })
    
    const totalCredit = computed(() => {
      return newVoucher.entries.reduce((sum, entry) => sum + (parseFloat(entry.credit_amount) || 0), 0)
    })
    
    // 方法
    const fetchVouchers = async () => {
      try {
        await financeStore.fetchVouchers(filters)
      } catch (error) {
        console.error('获取凭证失败:', error)
        alert('获取凭证失败: ' + (error.message || '未知错误'))
      }
    }
    
    const fetchAccountingSubjects = async () => {
      try {
        const response = await financeStore.fetchAccountingSubjects()
        accountingSubjects.value = response.data || []
      } catch (error) {
        console.error('获取会计科目失败:', error)
        alert('获取会计科目失败: ' + (error.message || '未知错误'))
      }
    }
    
    const addEntry = () => {
      newVoucher.entries.push({
        subject_id: '',
        debit_amount: 0,
        credit_amount: 0,
        description: ''
      })
    }
    
    const removeEntry = (index) => {
      if (newVoucher.entries.length > 1) {
        newVoucher.entries.splice(index, 1)
      } else {
        alert('至少需要保留一条分录')
      }
    }
    
    const updateCreditAmount = (index) => {
      // 当借方金额变化时，清空贷方金额
      newVoucher.entries[index].credit_amount = 0
    }
    
    const updateDebitAmount = (index) => {
      // 当贷方金额变化时，清空借方金额
      newVoucher.entries[index].debit_amount = 0
    }
    
    const createVoucher = async () => {
      if (!financeStore.isBalanced) {
        alert('借贷不平衡，请检查分录')
        return
      }
      
      try {
        await financeStore.createVoucher({
          period: newVoucher.period,
          summary: newVoucher.summary,
          entries: newVoucher.entries
        })
        
        showCreateModal.value = false
        resetNewVoucher()
        await fetchVouchers()
        alert('凭证创建成功')
      } catch (error) {
        console.error('创建凭证失败:', error)
        alert('创建凭证失败: ' + (error.message || '未知错误'))
      }
    }
    
    const viewVoucher = async (voucher) => {
      try {
        await financeStore.fetchVoucherDetail(voucher.id)
        showDetailModal.value = true
      } catch (error) {
        console.error('获取凭证详情失败:', error)
        alert('获取凭证详情失败: ' + (error.message || '未知错误'))
      }
    }
    
    const postVoucher = async (voucher) => {
      if (!confirm('确定要过账该凭证吗？')) return
      
      try {
        await financeStore.postVoucher(voucher.id)
        await fetchVouchers()
        alert('凭证过账成功')
      } catch (error) {
        console.error('凭证过账失败:', error)
        alert('凭证过账失败: ' + (error.message || '未知错误'))
      }
    }
    
    const resetNewVoucher = () => {
      newVoucher.period = format(new Date(), 'yyyy-MM')
      newVoucher.summary = ''
      newVoucher.entries = [
        {
          subject_id: '',
          debit_amount: 0,
          credit_amount: 0,
          description: ''
        }
      ]
    }
    
    const getStatusText = (status) => {
      const statusMap = {
        'DRAFT': '草稿',
        'POSTED': '已过账'
      }
      return statusMap[status] || status
    }
    
    const formatDateTime = (dateString) => {
      if (!dateString) return ''
      return format(new Date(dateString), 'yyyy-MM-dd HH:mm:ss')
    }
    
    // 初始化
    onMounted(async () => {
      await Promise.all([
        fetchVouchers(),
        fetchAccountingSubjects()
      ])
    })
    
    return {
      financeStore,
      showCreateModal,
      showDetailModal,
      filters,
      newVoucher,
      accountingSubjects,
      totalDebit,
      totalCredit,
      fetchVouchers,
      addEntry,
      removeEntry,
      updateCreditAmount,
      updateDebitAmount,
      createVoucher,
      viewVoucher,
      postVoucher,
      getStatusText,
      formatDateTime
    }
  }
}
</script>

<style scoped>
.finance-vouchers-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
}

.filter-section {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 4px;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 5px;
}

.filter-item label {
  white-space: nowrap;
}

.table-container {
  overflow-x: auto;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  background: white;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.data-table th,
.data-table td {
  padding: 12px 15px;
  text-align: left;
  border-bottom: 1px solid #dee2e6;
}

.data-table th {
  background-color: #f8f9fa;
  font-weight: 600;
}

.status-badge {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.status-badge.draft {
  background-color: #ffc107;
  color: #212529;
}

.status-badge.posted {
  background-color: #28a745;
  color: white;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
}

.btn-primary {
  background-color: #007bff;
  color: white;
}

.btn-primary:hover {
  background-color: #0056b3;
}

.btn-secondary {
  background-color: #6c757d;
  color: white;
}

.btn-secondary:hover {
  background-color: #545b62;
}

.btn-success {
  background-color: #28a745;
  color: white;
}

.btn-success:hover {
  background-color: #1e7e34;
}

.btn-info {
  background-color: #17a2b8;
  color: white;
}

.btn-info:hover {
  background-color: #117a8b;
}

.btn-danger {
  background-color: #dc3545;
  color: white;
}

.btn-danger:hover {
  background-color: #bd2130;
}

.btn-sm {
  padding: 4px 8px;
  font-size: 12px;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 800px;
  max-height: 90vh;
  overflow-y: auto;
}

.detail-modal {
  max-width: 1000px;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  border-bottom: 1px solid #dee2e6;
}

.modal-header h3 {
  margin: 0;
}

.modal-close {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #6c757d;
}

.modal-body {
  padding: 24px;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 16px 24px;
  border-top: 1px solid #dee2e6;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ced4da;
  border-radius: 4px;
  font-size: 14px;
}

.form-row {
  display: grid;
  grid-template-columns: 2fr 1fr 1fr 2fr auto;
  gap: 10px;
  align-items: end;
  margin-bottom: 10px;
}

.entries-section {
  margin: 20px 0;
}

.entries-section h4 {
  margin-bottom: 15px;
  border-bottom: 1px solid #dee2e6;
  padding-bottom: 5px;
}

.entry-item {
  padding: 15px;
  background: #f8f9fa;
  border-radius: 4px;
  margin-bottom: 10px;
}

.remove-entry {
  align-self: end;
  height: 38px;
}

.balance-info p {
  text-align: center;
  font-weight: 500;
  margin: 10px 0;
}

.balance-info .unbalanced {
  color: #dc3545;
}

.voucher-info {
  margin-bottom: 20px;
}

.voucher-info p {
  margin: 8px 0;
}

.text-center {
  text-align: center;
}
</style>